# -*- coding: utf-8 -*-
# @Author: fanmingxiang@touty.io
# @Date: 2023/3/31 22:10
import copy
import json
import os
import threading
from datetime import datetime
from json import JSONDecodeError
from time import sleep

import requests
from django.conf import settings
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from ApiAutoTestPlatform.settings import BASE_DIR
from apitests import models
from apitests.models import ApiDefine, ApiCase, ApiAutoTest, CaseTemporary
from common import config
from common.config import BASE_PATH
from common.pagination import Pagination
from common.read_sql import read_sql
from common.run_suite import run_suite
from common.threading_result import ThreadTimer
from projects.models import Projects, Modules
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

from test_reports.models import TestReports
from users.models import UserProfile


def api_define_list(request):
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    nums = request.GET.get('nums', None)
    search_text = request.GET.get('Search', '')
    search_dict = {}
    projects_list = Projects.objects.all().order_by('-create_time')
    is_project = int(request.COOKIES['Project'])
    if is_project:
        project_id = projects_list.get(id=is_project)
        modules_list = project_id.modules_set.all()
        modules_id_list = [modules.id for modules in modules_list]
        search_dict['module__in'] = modules_id_list
    if search_text:
        search_dict['name__contains'] = search_text
    api_defines_list = ApiDefine.objects.filter(**search_dict).order_by('-create_time')
    content = Pagination(api_defines_list, search_text, page, nums).per_page()
    content['projects_list'] = projects_list
    content['is_project'] = is_project
    return render(request, 'api_define_list.html', content)


def api_define_add(request):
    if request.method == 'GET':
        projects_list = Projects.objects.all().order_by('-create_time')
        is_project = int(request.COOKIES['Project'])
        project_id = projects_list.get(id=is_project)
        modules_list = project_id.modules_set.all()
        users = UserProfile.objects.all()
        api_defines_list = ApiDefine.objects.all()
        content = {
            'modules_list': modules_list,
            'users': users,
            'api_defines_list': api_defines_list,
            'projects_list': projects_list,
            'is_project': is_project,
        }
        return render(request, 'api_define_add.html', content)
    api_name = request.POST['api_name']
    api_module = request.POST['api_module']
    api_user = request.POST['api_user']
    api_status = request.POST['api_status']
    api_method = request.POST['api_method']
    api_url = request.POST['api_url']
    api_params = request.POST['api_params']
    api_headers = request.POST['api_headers']
    is_assert = request.POST['is_assert']
    body_choice = request.POST['body_choice']
    api_body = request.POST['api_body']
    assert_choice = request.POST['assert_choice']
    api_assert = request.POST['api_assert']
    api_describe = request.POST['api_describe']
    if (api_name and api_module and api_user and api_method and api_url):
        api_define = ApiDefine(name=api_name, module_id=api_module, interface=api_url, tester_id=api_user,
                               status=api_status, method=api_method, params=api_params, headers=api_headers,
                               body_type=body_choice, body=api_body, assert_type=assert_choice, assert_body=api_assert,
                               describe=api_describe, is_assert=is_assert)
        api_define.save()
        return JsonResponse({"status": True})

    return JsonResponse({"status": False, "error_msg": "信息未填写完整"})


def api_define_del(request):
    api_define_id = request.POST['api_define_id']
    ApiDefine.objects.filter(id=api_define_id).delete()
    return JsonResponse({"status": True})


def api_define_edit(request):
    if request.method == 'GET':
        projects_list = Projects.objects.all().order_by('-create_time')
        is_project = int(request.COOKIES['Project'])
        api_define_id = request.GET.get('api_define_id')
        api_define = ApiDefine.objects.get(id=api_define_id)
        project_id = Modules.objects.get(id=api_define.module_id).project_id
        modules = Projects.objects.get(id=project_id).modules_set.all()
        users = UserProfile.objects.all()
        params = json.loads(api_define.params)
        headers = json.loads(api_define.headers)
        body = json.loads(api_define.body)
        content = {
            'api_define': api_define,
            'users': users,
            "modules": modules,
            "params": params,
            "headers": headers,
            "body": body,
            "projects_list": projects_list,
            "is_project": is_project,
        }
        return render(request, 'api_define_edit.html', content)
    is_assert = request.POST['is_assert']
    api_id = request.POST['api_id']
    api_name = request.POST['api_name']
    api_module = request.POST['api_module']
    api_user = request.POST['api_user']
    api_status = request.POST['api_status']
    api_method = request.POST['api_method']
    api_url = request.POST['api_url']
    api_params = request.POST['api_params']
    api_headers = request.POST['api_headers']
    body_choice = request.POST['body_choice']
    api_body = request.POST['api_body']
    assert_choice = request.POST['assert_choice']
    api_assert = request.POST['api_assert']
    api_describe = request.POST['api_describe']
    if (api_name and api_module and api_user and api_method and api_url):
        ApiDefine.objects.filter(id=api_id).update(name=api_name, module_id=api_module, interface=api_url,
                                                   tester_id=api_user,
                                                   status=api_status, method=api_method, params=api_params,
                                                   headers=api_headers,
                                                   body_type=body_choice, body=api_body,
                                                   assert_type=assert_choice, assert_body=api_assert,
                                                   describe=api_describe, is_assert=is_assert)
        return JsonResponse({"status": True})

    return JsonResponse({"status": False, "error_msg": "信息未填写完整"})


def api_define_request_test(request):
    content_type = {0: 'text/html', 1: "application/json", 2: "text/plain", 3: "text/javascript", 4: "text/xml"}
    api_method = request.POST['api_method']
    api_url = request.POST['api_url']
    api_params = json.loads(request.POST['api_params'])
    api_headers = json.loads(request.POST['api_headers'])
    body_choice = int(request.POST['body_choice'])
    try:
        api_body = json.loads(request.POST['api_body'])
    except Exception as e:
        return JsonResponse({"status": False, "error_msg": "参数错误"})
    try:

        if api_method == "GET":
            rep = requests.get(url=api_url, headers=api_headers, params=api_params)
            rep_status_code = rep.status_code
            rep_json_data = rep.text
            rep_reason = rep.reason
            rep_time = int(rep.elapsed.total_seconds() * 1000)
            return JsonResponse({"status": True, "rep_status_code": rep_status_code, "rep_json_data": rep_json_data,
                                 "rep_reason": rep_reason, "rep_time": rep_time})

        if api_method == "POST":
            if body_choice == 1:
                api_headers['Content-Type'] = 'application/x-www-form-urlencoded'
            if body_choice == 2:
                rep = requests.post(url=api_url, headers=api_headers, params=api_params, json=api_body)
            else:
                rep = requests.post(url=api_url, headers=api_headers, params=api_params, data=api_body)
            rep_status_code = rep.status_code
            rep_json_data = rep.json()
            rep_reason = rep.reason
            rep_time = int(rep.elapsed.total_seconds() * 1000)
            return JsonResponse({"status": True, "rep_status_code": rep_status_code, "rep_json_data": rep_json_data,
                                 "rep_reason": rep_reason, "rep_time": rep_time})
    except requests.exceptions.MissingSchema as e:
        return JsonResponse({"status": False, "error_msg": "数据请求失败"})


def api_save_case(request):
    is_assert = request.POST['is_assert']
    api_id = request.POST['api_id']
    api_name = request.POST['api_name']
    api_method = request.POST['api_method']
    api_url = request.POST['api_url']
    api_params = request.POST['api_params']
    api_headers = request.POST['api_headers']
    body_choice = request.POST['body_choice']
    api_body = request.POST['api_body']
    assert_choice = request.POST['assert_choice']
    api_assert = request.POST['api_assert']
    if (api_name and api_method and api_url):
        api_case = ApiCase(name=api_name, api_define_id=api_id, interface=api_url,
                           method=api_method, params=api_params,
                           headers=api_headers,
                           body_type=body_choice, body=api_body, is_assert=is_assert,
                           assert_type=assert_choice, assert_body=api_assert,
                           )
        api_case.save()
        return JsonResponse({"status": True})


def test(request):
    if request.method == 'POST':
        params = request.POST.get('params')
        return JsonResponse({"status": True})
    return render(request, 'api_define_add2.html')
